/*
 @Date: 2022/4/29
 @Desc: 字符串扩展
 */

import UIKit
import Foundation
import CommonCrypto

extension String {
  
    /// 根据字符串创建控制器
    func ip2Vc()-> UIViewController? {
        guard let appName = Bundle.main.infoDictionary?["CFBundleName"] as? String else { return nil }
        let classStr = appName + "." + self
        guard let aCls = NSClassFromString(classStr) else { return nil }
        guard let type = aCls as? UIViewController.Type else {
            return nil
        }
        return type.init()
    }
    
    /// 转换成16进制
    func toHexString()->String? {
        guard let data = self.data(using: .utf8) else { return nil }
        let bytes = [UInt8](data)
        return bytes.map { it in
//            let bt = UInt8(it)
            return String.init(format: "%x", it&0xff)
        }.joined(separator: "")
    }
    
    
}

//MARK: hmac sha256加密相关
extension String {
    
    /// hmac sha1 加密
    func hmacsha256(_ key: String)-> String? {
        let target = self
        let op = kCCHmacAlgSHA256
        guard let cKey = key.cString(using: .utf8) else { return nil }
        guard let cTarget = target.cString(using: .utf8) else { return nil }
        var result = [CUnsignedChar](repeating: 0, count: Int(CC_SHA256_DIGEST_LENGTH))
        CCHmac(CCHmacAlgorithm(op), cKey, strlen(cKey), cTarget, strlen(cTarget), &result)
        let hmacData: NSData = NSData(bytes: result, length: Int(CC_SHA256_DIGEST_LENGTH))
        let hmacBase64 = hmacData.base64EncodedString(options: .lineLength76Characters)
        return hmacBase64
    }
    
    /// sha hash
    func shaHash()->String? {
        guard let chars = self.cString(using: .utf8) else { return nil }
        var result = [CUnsignedChar](repeating: 0, count: Int(CC_SHA256_DIGEST_LENGTH))
        CC_SHA256(chars, CC_LONG(strlen(chars)), &result)
        var sha256: String = ""
        for c in result {
            sha256 += String(format: "%02x", c)
        }
        return sha256.lowercased()
    }
}
